<?php

namespace App\Http\Controllers\Api\Order;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Service\CardService;

use App\Service\LockingService;

use Illuminate\Support\Facades\DB;

use App\Http\Controllers\Controller;

use App\Models\Card\CardCoupon;

use App\Models\Card\CardCouponCode;

use App\Models\Customer\Customer;

use App\Models\Promotion\PromotionOrderGiftCard;

use App\Models\Activity\Lottery\LotteryDrawFrequency;

use App\Models\Activity\Lottery\LotteryDrawFrequencySource;

use App\Models\Activity\Lottery\LotteryDraw;

use App\Models\Promotion\PromotionOrderGiftReceive;

use App\Models\Promotion\PromotionOrderGift;

use Illuminate\Support\Facades\Redis;

use App\Models\Promotion\PromotionOrderGiftReceiveCard as ReceiveCardModel;

class PromotionController extends  Controller {

    //卡券类型
    public static $card_type = [
        '1' => '代金券',
        '2' => '折扣券',
        '3' => '提货券',
        '4' => '通用券',
        '5' => '免运费券',
    ];

    /**
     * 抽奖类活动
     * @param Request $request
     * @return mixed
     */
    public function lottery ( Request $request ) {

        $id = $request->input('id',0);
        $bill_no = $request->input('order_no');
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id',session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }
        if ( !ebsig_is_int( $id ) ) {
            return response()->json(['code' => 10001, 'message' => '缺少参数：id']);
        }
        if ( empty( $bill_no ) ) {
            return response()->json(['code' => 10002, 'message' => '缺少参数：order_no']);
        }

        //查询会员信息
        $pcust_id = get_customer_id( $session_id , $platform );
        if ( !$pcust_id ) {
            return response()->json(['code' => 10003, 'message' => '会员未登录']);
        }

        //查询促销活动记录
        $receive_data = PromotionOrderGiftReceive::find( $id );
        if ( empty( $receive_data ) ) {
            return response()->json(['code' => 10004, 'message' => '下单活动不存在']);
        }
        if ( $receive_data->receive_status == 2 ) {
            return response()->json(['code' => 10005, 'message' => '领取中']);
        }
        if ( $receive_data->receive_status == 3 ) {
            return response()->json(['code' => 10006, 'message' => '已领取']);
        }
        if ( $receive_data->pcustID != $pcust_id || $receive_data->bill_no != $bill_no ) {
            return response()->json(['code' => 10007, 'message' => '领取失败']);
        }

        //查询促销活动
        $promotion_data = PromotionOrderGift::where(['id'=> $receive_data->promotion_id,'sub_type'=>$receive_data->promotion_type])->first();
        if ( empty( $promotion_data ) || $promotion_data->activity_id !=  $receive_data->activity_id  ) {
            return response()->json(['code' => 10008 , 'message' => '促销活动不存在' ]);
        }
        if ( $promotion_data->useFlg == 0  || $promotion_data->end_time < Carbon::now() ) {
            return response()->json(['code' => 10009 , 'message' => '促销活动已结束' ]);
        }

        //活动id
        $activity_id = $receive_data->activity_id;

        //检查活动
        $activity_data = LotteryDraw::find($activity_id);
        if ( empty( $activity_data ) ) {
            return response()->json(['code' => 10010 , 'message' => '活动不存在' ]);
        }
        if ( $activity_data->order_give == 0 ) {
            return response()->json(['code' => 10011 , 'message' => '活动未开启下单赠送' ]);
        }

        //赠送次数
        $give_num = $activity_data->order_give_num;

        //保存赠送次数
        $frequency_obj = LotteryDrawFrequency::where(['activity_id'=>$activity_id,'pcustID'=>$pcust_id])->first();
        if ( empty( $frequency_obj ) ) {
            $frequency_obj = new LotteryDrawFrequency();
            $frequency_obj->uuid = makeUuid();
            $frequency_obj->timeStamp = Carbon::now();
            $frequency_obj->creator = 'system';
            $frequency_obj->createTime = Carbon::now();
            $frequency_obj->activity_id = $activity_id;
            $frequency_obj->pcustID = $pcust_id;
        }
        $frequency_obj->frequency += $give_num;

        //保存赠送记录
        $send_log = [
            'uuid' => makeUuid(),
            'timeStamp' => Carbon::now(),
            'creator' => 'system',
            'createTime' => Carbon::now(),
            'activity_id' => $activity_id,
            'pcustID' => $pcust_id,
            'source' => 3,
            'frequency' => $give_num,
            'promotion_id' => 0,
            'share_id' => 0
        ];

        try {

            //开始事务
            DB::beginTransaction();

            //赠送次数
            $frequency_obj->save();

            //赠送记录
            LotteryDrawFrequencySource::insert( $send_log );

            //更新下单促销领取记录表数据
            $receive_data->increase_times = $give_num;
            $receive_data->receive_status = 3;
            $receive_data->save();

            //提交事务
            DB::commit();

        } catch ( \Exception $e) {

            //事务回滚
            DB::rollBack();

            return response()->json(['code' => 10012 , 'message' => '赠送失败']);

        }

        return response()->json(['code' => 200 , 'message' => '赠送成功' , 'data' => ['id'=>$activity_id] ]);

    }

    /*
     * 分享红包，拼手气红包领取人员记录
     */
    private static function getCache ( $id ) {

        $data = Redis::get('G_WDH_BILL_PROMOTION_CARD_RECEIVE_'.$id);
        if ( empty( $data ) ) {

            $data = [
                'pcustID' => [],
                'data' =>[]
            ];

            // 查询卡券领取表已领取的记录
            $where = [
                ['receive_id' , '=' , $id],
                ['user_id' , '!=' , '']
            ];
            $partake = ReceiveCardModel::where($where)->orderBy('id', 'DESC')->get()->toArray();

            if ( !empty( $partake ) ) {

                foreach ( $partake as $item ) {

                    //查询卡券信息
                    $coupon = CardCoupon::find( $item['card_id'] );
                    if ( empty( $coupon ) ) {
                        continue;
                    }

                    //查询会员信息
                    $customer = Customer::find($item['user_id']);
                    if ( empty( $customer ) ) {
                        continue;
                    }

                    $data['pcustID'][] = $item['user_id'];

                    if ( $item['type'] == 8 ) {
                        $data['data'][] = [
                            'card_id' => $item['card_id'],
                            'type' => $item['type'],
                            'mobile' => $customer->custID,
                            'pic' => $customer->head_pic,
                            'amount' => floatval( $coupon['amount'] ),
                            'most' => $item['most'],
                            'time' => date('m-d H:i:s',strtotime($item['timeStamp'])),
                            'pcustID' => $item['user_id']
                        ];
                    } else if ( $item['type'] ==  7 ) {
                        $data['data'][] = [
                            'card_id' => $item['card_id'],
                            'type' => $item['type'],
                            'mobile' => $customer->custID,
                            'pic' => $customer->head_pic,
                            'card_type' => self::$card_type[$coupon['card_type']],
                            'time' => date('m-d H:i:s',strtotime($item['timeStamp'])),
                            'speed' => $item['tips_win'],
                            'pcustID' => $item['user_id']
                        ];
                    }

                }

            }

            Redis::setex('G_WDH_BILL_PROMOTION_CARD_RECEIVE_'.$id, 604800 , json_encode($data) );

        } else {
            $data = json_decode( $data , true );
        }

        return $data;

    }

    /**
     * 领取红包
     * @param Request $request
     * @return mixed
     */
    public  function redPacket ( Request $request ) {

        $id = $request->input('id');
        $card_id = $request->input('card_id',0);
        $mobile = $request->input('mobile');
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id',session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }
        if ( empty( $id ) ) {
            return response()->json(['code' => 10001 , 'message' => '缺少参数：id' ]);
        }

        //查询会员信息
        if ( !empty( $mobile ) ) {
            $customer = Customer::where('custID',$mobile)->first();
            if ( empty( $customer ) ) {
                return response()->json(['code' => 10003 , 'message' => '会员不存在' ]);
            }
            $pcust_id = $customer->pcustID;
            $cust_id = $customer->custID;
            $pic = $customer->head_pic;
        } else {
            $customer = get_customer_login( $session_id , $platform );
            $pcust_id = $customer['pcustID'];
            $cust_id = $customer['custID'];
            $pic = '';

            if ( $pcust_id ) {
                $customer = Customer::find($pcust_id);
                if ( empty( $customer ) ) {
                    return response()->json(['code' => 10003 , 'message' => '会员不存在' ]);
                }
                $pic = $customer->head_pic;
            }
        }

        //实例卡券服务类
        $card_service = new CardService();

        //活动类型
        $type = 0;
        //可领取的卡券
        $red_packet = [];
        //获取已参与记录
        $partake = self::getCache( $id );

        /**
         * 1.未登录状态
         * 2.登陆已领取
         * 3.登陆未领取
         */
        if ( in_array($pcust_id,$partake['pcustID'] ) ) {

            foreach ( $partake['data'] as &$item ) {

                if ( $item['pcustID'] != $pcust_id ) {
                    unset( $item['pcustID'] );
                    continue;
                }

                $type = $item['type'];

                //查询卡券信息
                $coupon = CardCoupon::find( $item['card_id'] );
                if ( !empty( $coupon ) ) {
                    $red_packet = [
                        'id' => $item['card_id'],
                        'discount' => app_to_float( $coupon['discount']*10 ),
                        'amount' => app_to_float( floatval( $coupon['amount'] ) ),
                        'card_type' => app_to_int( $coupon['card_type'] ),
                        'use_start_time' => date('Y.m.d',strtotime($coupon['start_time'])),
                        'use_end_time' => date('Y.m.d',strtotime( $coupon['end_time'] )),
                        'description' => $coupon['description'],
                        'limit_money' => app_to_float( $coupon['limit_money'] ),
                        'card_name' => $coupon['card_name'],
                        'status' => 2
                    ];

                }

                unset( $item['pcustID'] );

            }

        } else {

            //查询领取记录
            $receive = PromotionOrderGiftReceive::find($id);
            if ( empty( $receive ) ) {
                return response()->json(['code' => 10005 , 'message' => '活动不存在' ]);
            }

            //活动类型
            $type = $receive->promotion_type;

            //领取状态
            if ( $receive->receive_status != 3 ) {
                //查询卡券领取表
                $where = [
                    ['receive_id' , '=' , $id],
                    ['user_id' , '=' , ''],
                    ['remark' , '=' , '']
                ];
                $receive_card = ReceiveCardModel::where($where)->orderBy('id', 'ASC')->get()->toArray();
                if ( $receive_card ) {

                    //查询促销活动
                    $promotion_data = PromotionOrderGift::where('id',$receive_card[0]['promotion_id'])->first();
                    if ( empty( $promotion_data ) ) {
                        return response()->json(['code' => 10005 , 'message' => '下单促销活动不存在' ]);
                    }
                    if ( $promotion_data->useFlg == 0  || $promotion_data->end_time < Carbon::now() ) {
                        return response()->json(['code' => 10006 , 'message' => '下单促销活动已结束' ]);
                    }

                    foreach ( $receive_card as $card ) {

                        //查询卡券信息
                        $coupon = CardCoupon::find( $card['card_id'] );
                        if ( empty( $coupon ) ) {
                            ReceiveCardModel::addRemark( $card['id'] , '卡券不存在');
                            continue;
                        } else {
                            $coupon = $coupon->toArray();
                        }

                        if ( $coupon['provide_type'] != 1 ) {
                            ReceiveCardModel::addRemark( $card['id'] , '卡券不是账户券，无法发放');
                            continue;
                        }

                        if ( $coupon['start_time'] > Carbon::now() || $coupon['end_time'] < Carbon::now() ) {
                            ReceiveCardModel::addRemark( $card['id'] , '卡券不在发放时间范围内');
                            continue;
                        }

                        if ( !$coupon['useFlg'] ) {
                            ReceiveCardModel::addRemark( $card['id'] , '卡券被禁用');
                            continue;
                        }

                        if ( $coupon['repeat_count'] > 0 ) {
                            $search_num =  CardCouponCode::where(['activity_id'=>$coupon['card_id'],'pcustID'=>$pcust_id])->count();
                            if ( $search_num >=  $coupon['repeat_count']  ) {
                                continue;
                            }
                        }

                        //判断剩余卡券数
                        if ( $coupon['getNum'] >= $coupon['total_num'] ) {
                            ReceiveCardModel::addRemark( $card['id'] , '卡券数量不足');
                            continue;
                        }

                        $status = 0;

                        //登陆状态直接发放卡券
                        if ( $pcust_id ) {

                            //加锁redis
                            $redis_index = 'G_WDH_BILL_PROMOTION_GIFT_RECEIVE_'. $id.$pcust_id;
                            if ( LockingService::check( $redis_index ) ) {
                                return response()->json(['code' => 10006 , 'message' => '请求频繁' ]);
                            }

                            //更新领取记录
                            $where = [
                                ['id','=',$card['id']],
                                ['user_id','=','']
                            ];
                            $save_res = ReceiveCardModel::where($where)->update(['user_id'=>$pcust_id]);
                            if ( !$save_res ) {
                                continue;
                            }

                            //发放卡券
                            $send_result = $card_service->grant( $coupon , 1 , $pcust_id , $cust_id , true );
                            if ( $send_result['code'] != 200 ) {
                                ReceiveCardModel::where($where)->update(['user_id'=>'']);
                                continue;
                            }

                            $status = 1;
                            if ( $card_id && $card_id != $card['card_id'] )  {
                                $status = 3;
                            }

                            if ( $card['type'] == 8 ) {
                                $partake['data'][] = [
                                    'card_id' => $card['card_id'],
                                    'type' => $card['type'],
                                    'mobile' => $customer->custID,
                                    'pic' => $customer->head_pic,
                                    'amount' => floatval( $coupon['amount'] ),
                                    'most' => $card['most'],
                                    'time' => date('m-d H:i:s',strtotime($card['timeStamp']))
                                ];
                            } else if ( $card['type'] ==  7 ) {
                                $partake['data'][] = [
                                    'card_id' => $card['card_id'],
                                    'type' => $card['type'],
                                    'mobile' => $customer->custID,
                                    'pic' => $customer->head_pic,
                                    'card_type' => self::$card_type[$coupon['card_type']],
                                    'time' => date('m-d H:i:s',strtotime($card['timeStamp'])),
                                    'speed' => $card['tips_win']
                                ];
                            }

                            Redis::del('G_WDH_BILL_PROMOTION_CARD_RECEIVE_'.$id);

                            //更新领取表的领取状态
                            if ( count( $receive_card ) == 1 ) {
                                PromotionOrderGiftReceive::where(['id'=>$card['receive_id']])->update(['receive_status'=>3]);
                            } else {
                                PromotionOrderGiftReceive::where(['id'=>$card['receive_id']])->update(['receive_status'=>2]);
                            }

                            LockingService::remove();

                        }

                        //卡券信息
                        $red_packet = [
                            'id' => $card['card_id'],
                            'discount' => app_to_float( $coupon['discount']*10 ),
                            'amount' => app_to_float( floatval( $coupon['amount'] ) ),
                            'card_type' => app_to_int( $coupon['card_type'] ),
                            'use_start_time' => date('Y.m.d',strtotime($coupon['start_time'])),
                            'use_end_time' => date('Y.m.d',strtotime( $coupon['end_time'] )),
                            'description' => $coupon['description'],
                            'limit_money' => app_to_float( $coupon['limit_money'] ),
                            'card_name' => $coupon['card_name'],
                            'status' => $status  // 0: 无提示 1：领取成功 2：已领取过 3：领取卡券和展示卡券不同
                        ];

                        if ( $type == 8  ) {
                            $red_packet['most'] = $card['most'];
                        }

                        break;

                    }

                }
            }
        }

        $data = [
            'pic' => $pic,
            'type' => app_to_int($type),
            'is_login' => app_to_int($pcust_id ? 1 : 0),
            'partake' => $partake['data'],
            'red_packet' => $red_packet,
            'remark' => nl2br('')
        ];

        return response()->json(['code' => 200 , 'message' => 'ok' , 'data' => $data ]);

    }



    /**
     * 赠送优惠券
     * @param Request $request
     * @return mixed
     */
    public function coupon( Request $request ) {

        $id = $request->input('id',0);
        $bill_no = $request->input('order_no');
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id',session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }
        if ( !ebsig_is_int( $id ) ) {
            return response()->json(['code' => 10001, 'message' => '缺少参数：id']);
        }
        if ( empty( $bill_no ) ) {
            return response()->json(['code' => 10002, 'message' => '缺少参数：order_no']);
        }

        //查询会员信息
        $customer = get_customer_login( $session_id , $platform );
        $pcust_id = $customer['pcustID'];
        $cust_id = $customer['custID'];
        if ( !$pcust_id ) {
            return response()->json(['code' => 10003, 'message' => '会员未登录']);
        }

        //查询促销活动记录
        $receive_data = PromotionOrderGiftReceive::find( $id );
        if ( empty( $receive_data ) ) {
            return response()->json(['code' => 10004, 'message' => '下单活动不存在']);
        }
        if ( $receive_data->receive_status == 2 ) {
            return response()->json(['code' => 10005, 'message' => '领取中']);
        }
        if ( $receive_data->receive_status == 3 ) {
            return response()->json(['code' => 10006, 'message' => '已参与']);
        }
        if ( $receive_data->pcustID != $pcust_id || $receive_data->bill_no != $bill_no ) {
            return response()->json(['code' => 10007, 'message' => '领取失败']);
        }

        //加锁redis
        $redis_index = 'G_WDH_BILL_PROMOTION_GIFT_RECEIVE_'. $id;
        if ( LockingService::check( $redis_index ) ) {
            return response()->json(['code' => 10020 , 'message' => '请求频繁']);
        }

        //查询促销活动
        $promotion_data = PromotionOrderGift::where(['id'=> $receive_data->promotion_id,'sub_type'=>$receive_data->promotion_type])->first();
        if ( empty( $promotion_data ) || $promotion_data->activity_id !=  $receive_data->activity_id  ) {
            LockingService::remove();
            return response()->json(['code' => 10008 , 'message' => '促销活动不存在' ]);
        }
        if ( $promotion_data->useFlg == 0  || $promotion_data->end_time < Carbon::now() ) {
            LockingService::remove();
            return response()->json(['code' => 10009 , 'message' => '促销活动已结束' ]);
        }

        //查询赠送卡券
        $receive_card = ReceiveCardModel::where(['receive_id'=>$receive_data->id,'pcustID'=>$pcust_id])->get()->toArray();
        if ( empty( $receive_card ) ) {
            LockingService::remove();
            return response()->json(['code' => 10010 , 'message' => '活动没有卡券可以赠送' ]);
        }

        //实例卡券服务类
        $card_service = new CardService();

        //赠送的卡券
        $send_card = [];

        try {

            //开始事务
            DB::beginTransaction();

            foreach ( $receive_card as $card ) {

                //查询卡券信息
                $coupon = CardCoupon::find( $card['card_id'] );
                if ( empty( $coupon ) ) {
                    ReceiveCardModel::addRemark( $card['id'] , '卡券不存在');
                    continue;
                } else {
                    $coupon = $coupon->toArray();
                }

                if ( $coupon['provide_type'] != 1 ) {
                    ReceiveCardModel::addRemark( $card['id'] , '卡券不是账户券，无法发放');
                    continue;
                }

                if ( $coupon['start_time'] > Carbon::now() || $coupon['end_time'] < Carbon::now() ) {
                    ReceiveCardModel::addRemark( $card['id'] , '卡券不在发放时间范围内');
                    continue;
                }

                if ( !$coupon['useFlg'] ) {
                    ReceiveCardModel::addRemark( $card['id'] , '卡券被禁用');
                    continue;
                }

                if ( $coupon['repeat_count'] > 0 ) {
                    $search_num =  CardCouponCode::where(['activity_id'=>$coupon['card_id'],'pcustID'=>$pcust_id])->count();
                    if ( $search_num >=  $coupon['repeat_count']  ) {
                        ReceiveCardModel::addRemark( $card['id'] , '卡券已超出重复领取次数');
                        continue;
                    }
                }

                //判断剩余卡券数
                if ( $coupon['getNum'] >= $coupon['total_num'] ) {
                    ReceiveCardModel::addRemark( $card['id'] , '卡券数量不足');
                    continue;
                }

                //发放卡券
                $send_result = $card_service->grant( $coupon , 1 , $pcust_id , $cust_id , false );  //发放卡券
                if ( $send_result['code'] != 200 ) {
                    ReceiveCardModel::addRemark( $card['id'] , '卡券发放失败：'.$send_result['message']);
                    continue;
                }

                if ( !isset( $send_card[ $card['card_id'] ] ) ) {
                    $send_card[ $card['card_id'] ] = [
                        'discount' => app_to_float( $coupon['discount']*10 ),
                        'amount' => app_to_float( floatval( $coupon['amount'] ) ),
                        'card_type' => app_to_int( $coupon['card_type'] ),
                        'use_start_time' => date('Y.m.d',strtotime($coupon['start_time'])),
                        'use_end_time' => date('Y.m.d',strtotime( $coupon['end_time'] )),
                        'description' => $coupon['description'],
                        'limit_money' => app_to_float( $coupon['limit_money'] ),
                        'card_name' => $coupon['card_name'],
                        'send_num' => 1
                    ];
                } else {
                    $send_card[ $card['card_id'] ]['send_num']++;
                }

            }

            //更新领取状态
            $where = [
                ['id' , '=' , $id ],
                ['receive_status' , '=' , 1]
            ];
            $save_res = PromotionOrderGiftReceive::where($where)->update(['receive_status'=>3]);
            if ( !$save_res ) {
                throw new \Exception( '领取状态更新失败', 10011 );
            }

            //提交事务
            DB::commit();

            $send_card = array_values($send_card);

        } catch ( \Exception $e) {

            //事务回滚
            DB::rollBack();

            LockingService::remove();

            if ( $e->getCode() > 0) {
                return response()->json(['code' => $e->getCode() , 'message' => $e->getMessage() ]);
            } else {
                return response()->json(['code' => 10012 , 'message' => '卡券领取失败' ]);
            }

        }

        //解锁
        LockingService::remove();

        return response()->json(['code' => 200 , 'message' => 'ok' , 'data' => $send_card ]);

    }

}

